package com.anran.netty.server.handler;

import com.anran.netty.message.ChatRequestMessage;
import com.anran.netty.message.ChatResponseMessage;
import com.anran.netty.server.session.SessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * 聊天消息处理器
 */
@ChannelHandler.Sharable
public class ChatRequestMessageHandler extends SimpleChannelInboundHandler<ChatRequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ChatRequestMessage msg) throws Exception {
        //传递对象
        String to = msg.getTo();
        //获取对方绑定的channel
        Channel channel = SessionFactory.getSession().getChannel(to);
        //对方在线
        if(channel != null){
            channel.writeAndFlush(new ChatResponseMessage(msg.getFrom(),msg.getContent()));
        }else {
            //离线
            ctx.writeAndFlush(new ChatResponseMessage(false,"对方用户不再线或不存在"));
        }
    }
}
